import unittest
from HTMLTestRunner.HTMLTestRunner import HTMLTestRunner
from email.utils import formataddr
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
from email.header import Header


# 任务一：继续开发减法，乘法，除法的用例

# 2.扫描刚才的4条用例
tests = unittest.defaultTestLoader.discover(r"D:\codes\Python\job\单元测试unittest", pattern="test*.py")

# 3.执行并生成测试报告
# HTMLTestRunner

runner = HTMLTestRunner(
    title="这是计算器报告",
    description="这是计算器报告",
    verbosity=2,  # 详细程度
    stream=open(file="计算器.html", mode="w+", encoding="utf-8")
)

runner.run(tests)

# 任务二：4.邮件发送代码，将刚才生成的测试报告做成附件发送到邮箱里
# 邮件配置信息
sender_email = 'wyguolai@163.com'  # 发件人邮箱地址
sender_password = 'ARUYHGWGTBPBAQEC'  # 发件人邮箱密码或授权码
receiver_emails = ['qaz242@foxmail.com']  # 接收人邮箱地址列表
subject = '这是一份测试报告，请查收！'  # 邮件主题
html_file_path = '计算器.html'  # HTML 文件的路径

# 创建邮件对象
msg = MIMEMultipart()
msg['Subject'] = Header(subject, 'utf-8')  # 设置主题，并指定字符编码
msg['From'] = formataddr((str(Header('随便', 'utf-8')), sender_email))   # 设置发件人名称，并指定字符编码
msg['To'] = Header(', '.join(receiver_emails), 'utf-8')  # 设置收件人名称，并指定字符编码

# 读取 HTML 文件内容
with open(html_file_path, 'r', encoding='utf-8') as file:
    html_content = file.read()

# 创建 HTML 正文
html_part = MIMEText(html_content, 'html')
msg.attach(html_part)

# 读取附件文件
attachment_file_path = '计算器.html'  # 附件文件的路径
attachment_filename = '计算器.html'  # 附件文件的名称

with open(attachment_file_path, 'rb') as file:
    attachment = MIMEBase('application', 'octet-stream')
    attachment.set_payload(file.read())
    encoders.encode_base64(attachment)
    encoded_filename = Header(attachment_filename, 'utf-8').encode()
    attachment.add_header('Content-Disposition', f'attachment; filename="{encoded_filename}"')
    msg.attach(attachment)

# 发送邮件
try:
    with smtplib.SMTP_SSL('smtp.163.com', 465) as server:
        server.login(sender_email, sender_password)
        server.sendmail(sender_email, receiver_emails, msg.as_string())
    print('邮件发送成功！')
except Exception as e:
    print('邮件发送失败:', e)
